<template>
  <!--竞争对手-->
  <div class="com">
    <!--竞争对手查找-->
    <el-row>
      <span style="padding: 0 10px"><i class="font-14 el-icon-s-open"></i></span>
      <el-select v-model="filterValue" @change="initData(currPage,pageSize,filterValue,vagueValue,content)" placeholder="全部数据" style="width: 120px">
        <el-option v-for="item in filterOptions" :key="item.value"
                   :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <span style="padding: 0 10px 0 30px"><i class="fn el-icon-message-solid"></i></span>
      <el-input v-model="content" clearable placeholder="请输入内容" style="width: 150px"></el-input>
      <el-select v-model="vagueValue"  @change="initData(currPage,pageSize,filterValue,vagueValue,content)" placeholder="竞争对手公司名称" style="width: 180px">
        <el-option v-for="item in vagueOptions" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <el-button @click="initData(currPage,pageSize,filterValue,vagueValue,content)" icon="el-icon-search" size="small" circle></el-button>
    </el-row>
    <!--新建竞争对手-->
    <div style="margin-top: 15px;overflow: hidden;">
      <el-col :span="12">
        <span>竞争对手</span>
        <small class="text-muted font-13">共{{totalSize}}条</small>
      </el-col>
      <el-col :span="12" class="text-right">
        <el-button type="text" @click="dialogFormVisible = true">
          <el-button size="small" icon="el-icon-circle-plus-outline">新建</el-button>
        </el-button>
      </el-col>
      <!--竞争对手dialog-->
      <el-dialog title="竞争对手" :visible.sync="dialogFormVisible" @close="closeDialog" width="60%" style="color: #333333"  >
        <el-form ref="com" :model="competitor" label-width="100px" :rules="rules">
          <el-divider></el-divider>
          <el-row>
            <el-col>
              <el-form-item label="公司名称:" prop="competitorName">
                <el-input v-model="competitor.competitorName" placeholder="" style="width: 91%"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="客户:" prop="customerByCustomerId.customerName">
                <el-input :disabled="true" v-model="competitor.customerByCustomerId.customerName" placeholder="" style="width: 91%"></el-input>
              </el-form-item>
              <div class="form-inline" v-show="customerBoxShow">
                <el-input v-model="customerValue" clearable size="medium" placeholder="拼音.字母.关键字" style="width: 20%"></el-input>
                <el-button @click="findCustomer" size="medium" icon="el-icon-search"></el-button>
                <el-popover placement="top" v-model="visible">
                  <div style="margin-bottom: 10px">
                    <span>查询条件:{{customerValue}}</span>
                    <span @click="cleanCustomer" class="cursor" style="float: right"><i class="el-icon-error"></i></span>
                  </div>
                  <ul class="cu-ul" v-if="customerList2 != ''">
                    <li @click="choiceCustomer2(item)" v-for="item in customerList2">{{item.customerName}}</li>
                  </ul>
                  <div style="margin: 5px 0;text-align: center" v-if="customerList2 == ''">
                    <i class="el-icon-warning-outline"/>没有符合条件的客户！
                  </div>
                </el-popover>
                <el-tooltip class="item" effect="dark" content="浏览选择客户" placement="bottom">
                  <el-button @click="innerVisible(cusCurrPage,cusPageSize)" size="medium" icon="el-icon-s-operation"></el-button>
                </el-tooltip>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="对应机会:" prop="opportunityByOppId">
                <el-select v-model="competitor.opportunityByOppId" value-key="oppId"  placeholder="未选" style="width: 91%">
                  <el-option v-for="item in opportunityList" :key="item.oppId" :label="item.oppTheme" :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="价格:" prop="competitorPrice">
                <el-input v-model.number="competitor.competitorPrice" placeholder="" style="width: 79%"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="竞争能力:">
                <el-select v-model="competitor.competitorCapacity" placeholder="未选" style="width: 79%">
                  <el-option v-for="item in jzOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="竞争/方案:">
                <el-input v-model="competitor.competitorProduct" type="textarea" style="width: 91%" :autosize="{ minRows: 2, maxRows: 4}"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="优势:">
                <el-input v-model="competitor.competitorStrengths" type="textarea" style="width: 91%" :autosize="{ minRows: 2, maxRows: 4}" ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="劣势:">
                <el-input v-model="competitor.competitorWeaknesses" type="textarea" style="width: 91%" :autosize="{ minRows: 2, maxRows: 4}" ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="应对策略:">
                <el-input v-model="competitor.competitorStrategy" type="textarea" style="width: 91%" :autosize="{ minRows: 2, maxRows: 4}" ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注:">
                <el-input v-model="competitor.competitorRemarks" type="textarea" style="width: 91%" :autosize="{ minRows: 2, maxRows: 4}" ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12" :offset="7">
              <el-form-item>
                <el-button @click="addCompetitor" type="primary">保存</el-button>
                <el-button @click="dialogFormVisible = false">取消</el-button>
              </el-form-item>
            </el-col>
          </el-row>
          <!--内层dialog-->
          <el-dialog width="30%" title="客户选择" :visible.sync="innerDialog" append-to-body>
            <!--选择客户-->
            <el-table :data="customerList" style="width: 100%">
              <el-table-column prop="customerId" label="客户编号" >
              </el-table-column>
              <el-table-column prop="customerName" label="客户名" >
              </el-table-column>
              <el-table-column label="请选择" >
                <template slot-scope="scope">
                  <el-button size="mini" @click="choiceCustomer(scope.row)" icon="el-icon-check" type="primary" circle style="margin-left: 10px"></el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-row style="margin-top:10px">
              <el-col :span="16">
                <el-pagination layout="prev, pager, next, jumper" :total="cusTotalSize" @current-change="cusChangePage"
                               :current-page.sync="cusCurrPage" :page-size="cusPageSize"></el-pagination>
              </el-col>
            </el-row>
          </el-dialog>
        </el-form>
      </el-dialog>
    </div>
    <!--竞争对手表格-->
    <el-table ref="multipleTable" :data="competitorList" tooltip-effect="dark" id="outTable"
              style="width: 100%" border :header-cell-style="rowClass" @selection-change="handleSelectionChange">
      <el-table-column type="selection" ></el-table-column>
      <el-table-column prop="competitorId" label="ID" sortable></el-table-column>
      <el-table-column prop="competitorName" label="公司名称" >
        <template slot-scope="scope">
          <div style="color: #333333" class="cursor" @click="handleEdit(scope.row)">
            <i class="el-icon-caret-right"></i>
            <span>{{scope.row.competitorName}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="competitorPrice" label="价格" sortable></el-table-column>
      <el-table-column prop="competitorCapacity" label="竞争能力" >
        <template slot-scope="scope">
          <span v-if="scope.row.competitorCapacity == 1">{{jzOptions[0].label}}</span>
          <span v-if="scope.row.competitorCapacity == 2">{{jzOptions[1].label}}</span>
          <span v-if="scope.row.competitorCapacity == 3">{{jzOptions[2].label}}</span>
          <span v-if="scope.row.competitorCapacity == 4">{{jzOptions[3].label}}</span>
        </template>
      </el-table-column>
      <el-table-column label="对应机会" >
        <template slot-scope="scope">
          <div style="color: #333333">
            <span>{{scope.row.opportunityByOppId.oppTheme}}</span>
            <el-tooltip class="item" effect="dark" content="打开详细页面" placement="bottom">
              <router-link :to="{path:'/opportview',query: {oppId: scope.row.opportunityByOppId.oppId}}">
                <span style="color: #333333">
                  <i class="el-icon-s-cooperation"></i>
                </span>
              </router-link>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="客户" >
        <template slot-scope="scope">
          <div style="color: #333333">
            <span>{{scope.row.customerByCustomerId.customerName}}</span>
            <el-tooltip class="item" effect="dark" content="打开详细页面" placement="bottom">
              <router-link :to="{path:'/customerview',query: {customerId: scope.row.customerByCustomerId.customerId}}">
                <span style="color: #333333">
                  <i class="el-icon-s-cooperation"></i>
                </span>
              </router-link>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="105px">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="编辑" placement="bottom">
            <el-button size="mini" @click="handleEdit(scope.row)"
                       icon="el-icon-edit" type="primary" circle style="margin-left: 10px"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="bottom">
            <el-button size="mini" @click="handleDelete(scope.row)"
                       icon="el-icon-delete" type="danger" circle></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-row style="margin-top:10px">
      <el-col :span="8">
        <el-tooltip class="item" effect="dark" content="删除" placement="bottom">
          <el-button style="padding: 12px 12px" icon="el-icon-delete" @click="handleDeleteMany" type="danger"></el-button>
        </el-tooltip>
      </el-col>
      <el-col :span="13">
        <el-pagination layout="sizes,prev,pager, next, jumper" :total="totalSize" @current-change="changePage"
                       :current-page.sync="currPage" :page-size="pageSize" :page-sizes="pageSizes" @size-change="changeSize"></el-pagination>
      </el-col>
      <el-col :span="3">
        <el-tooltip class="item" effect="dark" content="打印列表" placement="bottom">
          <el-button @click="handleWindowPrint('#outTable', '列表打印')" style="padding: 12px 12px" type="info" plain  icon="el-icon-printer"></el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="批量导出Excel格式数据" placement="bottom">
          <el-button @click="batchExportExcel" style="padding: 12px 12px" type="info" plain  icon="el-icon-document-copy"></el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="导出Excel格式数据" placement="bottom">
          <el-button @click="exportExcel" style="padding: 12px 12px" type="info" plain  icon="el-icon-document-remove"></el-button>
        </el-tooltip>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import XLSX from "xlsx";
  import FileSaver from "file-saver";

  export default {
  data () {
    return {
      emp:{},
      dialogFormVisible: false,
      competitorList: [], // 报价集合分页
      customerList: [], // 员工客户名称
      opportunityList: [],// 销售机会集合
      pageSize: 10, // 分页页大小
      pageSizes:[10,20,30],//页大小数组
      currPage: 1, // 当前页码，默认为1
      totalSize: 0, // 总记录数
      cusPageSize: 5, // 分页页大小
      cusCurrPage: 1, // 当前页码，默认为1
      cusTotalSize: 0, // 总记录数
      competitor: {
        competitorId: 0,
        competitorName: '',
        competitorPrice: '',
        competitorCapacity: '',
        competitorProduct: '',
        competitorStrengths: '',
        competitorWeaknesses: '',
        competitorStrategy: '',
        competitorRemarks: '',
        opportunityByOppId: '',
        customerByCustomerId: {}
      },
      customerBoxShow: true, // 客户搜索显示
      innerDialog: false,// 内层dialog客户
      content: '',// input内容
      customerValue:'',// 模糊查询客户查询值
      customerList2:[],// 模糊查询客户集合
      visible: false,// 模糊搜索ul显示
      mulSelection: [],
      rules: {
        competitorName: [{
          required: true,
          message: '必须填',
          trigger: 'blur'
        }, {
          min: 2,
          max: 8,
          message: '长度在 2 到 8 个字符',
          trigger: 'blur'
        }],
        opportunityByOppId: [
          { required: true, message: '请选择机会', trigger: 'change' }
        ],
        'customerByCustomerId.customerName': [
          { required: true, message: '请选择客户', trigger: 'blur' }
        ],
        competitorPrice: [
          { required: true, message: '必须填'},
          { type: 'number', message: '必须为数字'}
        ]
      },
      filterOptions: [{
        value: 0,
        label: '全部数据'
      }, {
        value: 1,
        label: '核心竞争'
      }, {
        value: 2,
        label: '有力竞争'
      }, {
        value: 3,
        label: '一般竞争'
      }, {
        value: 4,
        label: '忽略竞争'
      }],
      filterValue: 0,
      jzOptions: [{
        value: 1,
        label: '核心竞争'
      }, {
        value: 2,
        label: '有力竞争'
      }, {
        value: 3,
        label: '一般竞争'
      }, {
        value: 4,
        label: '忽略竞争'
      }],
      vagueOptions: [{
        value: 1,
        label: '竞争对手公司名'
      }, {
        value: 2,
        label: '客户名称'
      }],
      vagueValue: 1,
      selectList:[]
    }
  },
  methods: {
    // 查询当前员工
    loginEmp(){
      this.$axios.get('http://localhost:8088/emp')
        .then(v => {
          this.emp = v.data
        })
        .catch(function (v) {})
    },
    // 分页查询所有需求
    initData (currPage, pageSize,filter,vague,content) {
      this.$axios.get('http://localhost:8088/competitor-list', {
        params: {
          page: currPage,
          size: pageSize,
          filter:filter,
          vague:vague,
          content:content
        }
      })
        .then(v => {
          this.competitorList = v.data.rows
          this.totalSize = v.data.total
        })
        .catch(function (v) {})
    },
    // 报价表格分页
    changePage (val) {
      // val就是当前页码
      this.initData(val, this.pageSize,this.filterValue,this.vagueValue,this.content)
    },
    //改变页大小
    changeSize(val){
      this.pageSize = val
      this.currPage = 1
      this.initData(this.currPage,this.pageSize,this.filterValue,this.vagueValue,this.content)
    },
    // 查询客户所有机会
    opportunityData (cusId) {
      this.$axios.get('http://localhost:8088/cus-opp-list-all', {
        params:{
          cusId:cusId
        }
      })
        .then(v => {
          this.opportunityList = v.data
        })
        .catch(function (v) {})
    },
    // 修改数据回显
    handleEdit (val) {
      this.dialogFormVisible = true
      this.competitor.competitorId = val.competitorId
      this.competitor.competitorName = val.competitorName
      this.competitor.competitorPrice = val.competitorPrice
      this.competitor.competitorCapacity = val.competitorCapacity
      this.competitor.competitorProduct = val.competitorProduct
      this.competitor.competitorStrengths = val.competitorStrengths
      this.competitor.competitorWeaknesses = val.competitorWeaknesses
      this.competitor.competitorStrategy = val.competitorStrategy
      this.competitor.competitorRemarks = val.competitorRemarks
      this.competitor.opportunityByOppId = val.opportunityByOppId
      this.competitor.customerByCustomerId = val.customerByCustomerId
      this.opportunityData(val.customerByCustomerId.customerId)
      this.customerBoxShow = false
    },
    // 关闭dialog事件
    closeDialog () {
      this.$refs.com.resetFields()
      this.competitor = {
        competitorId: 0,
        competitorName: '',
        competitorPrice: '',
        competitorCapacity: '',
        competitorProduct: '',
        competitorStrengths: '',
        competitorWeaknesses: '',
        competitorStrategy: '',
        competitorRemarks: '',
        opportunityByOppId: '',
        customerByCustomerId:{}
      }
      this.customerBoxShow = true
      this.opportunityList = []
    },
    // 新增、修改
    addCompetitor () {
      this.$refs.com.validate((valid) => {
        if (valid) {
          this.$axios.post('http://localhost:8088/save-competitor',this.competitor)
            .then(v => {
              // 1、刷新数据
              this.initData(this.currPage,this.pageSize,this.filterValue,this.vagueValue,this.content)
              // 2、关闭弹框
              this.dialogFormVisible = false
              this.$message({
                message: '已保存',
                type: 'success'
              });
            })
            .catch(function (v) {})
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 打开内层dialog
    innerVisible (cusCurrPage,cusPageSize) {
      this.$axios.get('http://localhost:8088/emp-customer-list', {
        params: {
          page: cusCurrPage,
          size: cusPageSize,
        }
      })
        .then(v => {
          this.customerList = v.data.rows
          this.cusTotalSize = v.data.total
        })
        .catch(function (v) {})
      this.innerDialog = true
    },
    // 查询客户分页
    cusChangePage (val) {
      // val就是当前页码
      this.innerVisible(val, this.cusPageSize)
    },
    // 选择客户
    choiceCustomer(val){
      this.competitor.customerByCustomerId = val
      this.competitor.opportunityByOppId = ''
      this.opportunityData(val.customerId)
      this.innerDialog = false;
    },
    // 模糊查询客户
    findCustomer(){
      if (this.customerValue != ''){
        this.visible = true
        this.$axios.get('http://localhost:8088/emp-fuzzy-customer-list', {
          params: {
            customerName: this.customerValue
          }
        })
          .then(v => {
            this.customerList2 = v.data
          })
          .catch(function (v) {})
      }else {
        this.visible = false
      }
    },
    // 模糊选择客户
    choiceCustomer2(val){
      this.competitor.customerByCustomerId = val
      this.competitor.opportunityByOppId = ''
      this.opportunityData(val.customerId)
      this.visible = false
      this.customerValue = ''
    },
    // 失去焦点关闭模糊搜索框
    cleanCustomer(){
      this.visible = false
      this.customerValue = ''
    },
    // 删除提示
    handleDelete (val) {
      this.$confirm('此操作将永久删除该竞争, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteCom(val.competitorId)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 批量删除提示
    handleDeleteMany () {
      this.$confirm('此操作将永久删除勾选竞争, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteAll()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 获取批量删除对象集合
    handleSelectionChange (val) {
      this.mulSelection = val
    },
    // 删除axios
    deleteCom(competitorId){
      this.$axios.post('http://localhost:8088/delete-competitor', this.qs.stringify({competitorId: competitorId}))
        .then(v => {
          this.initData(this.currPage,this.pageSize,this.filterValue,this.vagueValue,this.content)
        })
        .catch(function (v) {})
    },
    // 删除所有
    deleteAll () {
      this.mulSelection.forEach(row => {
        this.deleteCom(row.competitorId)
      })
    },
    // pdf打印
    handleWindowPrint (ele, fileName) {
      document.body.innerHTML = document.querySelector(ele).outerHTML
      // 转异步 等待dom元素渲染（样式）完毕在打印
      setTimeout(() => {
        // 打印
        window.print()
        // 刷新页面
        window.location.reload()
      }, 20)
    },
    //导出excel
    exportExcel () {
      var xlsxParam = { raw: true };//转换成excel时，使用原始的格式
      var wb = XLSX.utils.table_to_book(document.querySelector("#outTable"),xlsxParam);
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream;charset=utf-8" }),
          "竞争导出.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    //批量导出excel batchList
    batchExportExcel(){
      this.mulSelection.forEach((item,i)=>{
        this.$set(item,'competitorId',item.competitorId);
        this.$set(item,'competitorName',item.competitorName);
        this.$set(item,'competitorPrice','￥'+item.competitorPrice);
        this.$set(item,'competitorCapacity',item.competitorCapacity);
        this.$set(item,'oppTheme',item.opportunityByOppId.oppTheme);
        this.$set(item,'customerName',item.customerByCustomerId.customerName);
        this.selectList.splice(i,0,item);
      })
      //excel数据导出
      require.ensure([], () => {
        const {
          export_json_to_excel
        } = require('../js/Export2Excel');
        const tHeader = ['ID','公司名称','价格','竞争能力','对应机会','客户'];
        const filterVal = ['competitorId','competitorName','competitorPrice','competitorCapacity','oppTheme','customerName'];
        const list = this.selectList;
        const data = this.formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, '竞争批量导出');
      })
      this.initData(this.currPage, this.pageSize,this.filterValue,this.vagueValue,this.content)
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    // 表头靠左样式
    rowClass(){
      return "text-align:left"
    },
  },
  created() {
    this.loginEmp()
    this.initData(this.currPage,this.pageSize,this.filterValue,this.vagueValue,this.content)
  }
}
</script>

<style>
</style>


